//
//  YFAlertsViewController.m
//  YFListenStock
//
//  Created by ChinaRainbow-iOS on 2019/2/14.
//  Copyright © 2019 ChinaRainbow-iOS. All rights reserved.
//

#import "YFAlertsLsitViewController.h"
#import "YFHomeCollectionReusableView.h"
#import "YFHomeCollectionReusableFooterView.h"
#import "YFVoice60sCollectionViewCell.h"
#import "YFHomeViewModel.h"
#import "ATVideoWindowView.h"
#import "YFVoiceToTextView.h"
@interface YFAlertsLsitViewController ()
<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UITextFieldDelegate>
@property (nonatomic, strong)NSMutableArray *voice60sHotArray;// 语音60s热门

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, assign) NSInteger currentIndex;
@property (assign, nonatomic) NSInteger page;
@property (assign, nonatomic) NSInteger per_page;
@end

@implementation YFAlertsLsitViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.atTitle = @"盘中快讯";
    self.currentIndex = -1;
    self.page = 1;
    self.per_page = 20;
    [self initFirstView];
}

-(void)initFirstView{
    // 主视图colleectionView
    [self setUpUI];
    [self.collectionView.mj_header beginRefreshing];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self showNavLightSepaLine];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self showNavLightSepaLine];
}
-(void)setUpUI{
    self.collectionView = ({
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT - [YFUITool naviHeight]) collectionViewLayout:layout];
        collectionView.backgroundColor = [UIColor whiteColor];
        collectionView.delegate = self;
        collectionView.dataSource = self;
        [collectionView registerClass:[YFHomeCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"YFHomeCollectionReusableView"];
        [collectionView registerClass:[YFHomeCollectionReusableFooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"YFHomeCollectionReusableFooterView"];
        
        [collectionView registerClass:[YFVoice60sCollectionViewCell class] forCellWithReuseIdentifier:@"YFVoice60sCollectionViewCell"];
        
        [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
        collectionView.showsVerticalScrollIndicator = NO;
        collectionView.showsHorizontalScrollIndicator = NO;
        [self.view addSubview:collectionView];
        adjustsScrollViewInsets(collectionView);
        [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_equalTo(0);
            make.top.mas_equalTo(0);
        }];
        [collectionView registerNib:[UINib nibWithNibName:@"ResourceCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"ResourceCollectionViewCell"];
        
        collectionView;
    });
    
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
}
-(void)loadNewData{
    self.page = 1;
    [self requestList];
}
-(void)loadMoreData{
    self.page++;
    [self requestList];
}

#pragma mark 网络请求
-(void)requestList{
    // 热门语音
    [YFHomeViewModel request_voicesHotListWithPer_page:20 page:self.page complete:^(NSDictionary *error, NSDictionary *result) {
        if (result) {
            if (self.page == 1) {
                [self.voice60sHotArray removeAllObjects];
            }
            // 语音60s
            NSArray *voices = result[@"voices"];
            for (int i = 0; i < voices.count ;i++ ) {
                NSDictionary *dict = [voices safeObjectWithIndex:i];
                YFVoice60SModel *model = [YFVoice60SModel yy_modelWithDictionary:dict];
                CGFloat height = [model.title mt_heightWithWidth:WINDOW_WIDTH - 37-81 font:[UIFont systemFontOfSize:15] ];
                if (height > 24) {
                    model.cellHeight = 75;
                }else{
                    model.cellHeight = 60;
                }
                if ([model.Id integerValue] == [[ATVideoWindowView shareView].model.Id integerValue]) {
                    model.isPlaying = YES;
                    self.currentIndex = i;
                }
                [self.voice60sHotArray safeAddObj:model];
            }
            NSDictionary *meta = [result objectForKey:@"meta"];
            NSDictionary *pagination = [meta objectForKey:@"pagination"];
            NSString *total = [NSString stringWithFormat:@"%@",[pagination objectForKey:@"total"]];
            if (self.voice60sHotArray.count < [total integerValue]) {
                self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
            }else{
                self.collectionView.mj_footer = nil;
            }
        }
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
    }];
}

#pragma mark - CollectionView delegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.voice60sHotArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    YFVoice60sCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"YFVoice60sCollectionViewCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    
    cell.model = [self.voice60sHotArray safeObjectWithIndex:indexPath.row];
    if (indexPath.row == self.voice60sHotArray.count - 1) {
        cell.yfBottomLineLabel.hidden = YES;
    }
    [cell.yfToTextBtn addTarget:self action:@selector(voiceTotext:) forControlEvents:UIControlEventTouchUpInside];
    cell.yfToTextBtn.tag = indexPath.row;
    
    [cell.yfPlayBtn addTarget:self action:@selector(playVoice60s:) forControlEvents:UIControlEventTouchUpInside];
    cell.yfPlayBtn.tag = indexPath.row;
    
    yfweakify(self);
    cell.yfBottomBtnClick = ^(YFModelChangeType type, YFVoice60SModel *model) {
        yfstrongify(self);
        [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
        [ATVideoWindowView shareView].model = model;
    };
    
    return cell;
}


// 播放
-(void)playVoice60s:(UIButton *)sender{
    __block NSInteger tag = sender.tag;
    [ATVideoWindowView shareView].isPlayNormalVoice60s = YES;
    [ATVideoWindowView shareView].allVoice60sModelArray = [self.voice60sHotArray copy];
    [ATVideoWindowView shareView].currentIndex = tag;
    
    YFVoice60SModel *model = [self.voice60sHotArray safeObjectWithIndex:tag];
    YFVoice60SModel *currentModel = [ATVideoWindowView shareView].model;
    
    if (currentModel && [self.voice60sHotArray containsObject:currentModel]) {
        self.currentIndex = ATVideoWindowView.shareView.currentIndex;
        currentModel.isPlaying = NO;
        [self.voice60sHotArray replaceObjectAtIndex:self.currentIndex withObject:currentModel];
        if (self.currentIndex == tag) {
            [self.collectionView reloadData];
            [ATVideoWindowView shareView].model = [YFVoice60SModel new];
            [[ATVideoWindowView shareView] closeStop];
            return;
        }
    }
    // 先暂停其他的
    if (([ATVideoWindowView.shareView.model.Id integerValue] > 0  ) &&  (ATVideoWindowView.shareView.isPlayNormalVoice60s == YES)) {
        currentModel.isPlaying = NO;
        [self.voice60sHotArray replaceObjectAtIndex:self.currentIndex withObject:currentModel];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.currentIndex inSection:0];
        [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
    }
    [ATVideoWindowView showViewPlayWithModel:model];
    
    model.isPlaying = YES;
    [self.voice60sHotArray replaceObjectAtIndex:sender.tag withObject:model];
    [self.collectionView reloadData];
    yfweakify(self);
    [ATVideoWindowView shareView].yfPlayStatusBlock = ^(NSInteger status) {
        yfstrongify(self);
        model.isPlaying = NO;
        NSIndexPath *indexPath2 = [NSIndexPath indexPathForRow:tag inSection:0];
        [self.voice60sHotArray replaceObjectAtIndex:tag withObject:model];
        [self.collectionView reloadItemsAtIndexPaths:@[indexPath2]];
        self.currentIndex = -1;
    };
    self.currentIndex = sender.tag;
    // 更新变化
    [ATVideoWindowView shareView].yfBottomBtnClick = ^(YFModelChangeType type, YFVoice60SModel * _Nonnull model) {
        yfstrongify(self);
        [self.voice60sHotArray replaceObjectAtIndex:ATVideoWindowView.shareView.currentIndex withObject:model];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:ATVideoWindowView.shareView.currentIndex inSection:0];
        [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
    };
}
// 语音转文字
-(void)voiceTotext:(UIButton *)sender
{
    YFVoice60SModel *tempModel = [self.voice60sHotArray safeObjectWithIndex:sender.tag];
    [YFVoiceToTextView shareView].hidden = NO;
    [YFVoiceToTextView shareView].yfTiitleLabel.text = tempModel.title;
    [YFVoiceToTextView shareView].yfContentView.text = tempModel.text;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    YFVoice60SModel *model = [self.voice60sHotArray safeObjectWithIndex:indexPath.row];
    if (model.isPlaying) {
        return CGSizeMake(WINDOW_WIDTH,model.cellHeight+8);
    }
    return CGSizeMake(WINDOW_WIDTH,model.cellHeight);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(WINDOW_WIDTH, 0);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeMake(WINDOW_WIDTH, 0);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    switch (indexPath.section) {
        case 0:
        {}
            break;
        case 3:
        {
        }
            break;
        case 2:
        {
        }
            break;
        default:
            break;
    }
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    //写你要实现的：页面跳转的相关代码
    
    return NO;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark lazy load

-(NSMutableArray *)voice60sHotArray{
    if (_voice60sHotArray == nil) {
        _voice60sHotArray = [NSMutableArray arrayWithCapacity:5];
    }
    return _voice60sHotArray;
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end



